package cn.tedu.mall.search.service.impl;

import cn.tedu.mall.common.restful.JsonPage;
import cn.tedu.mall.pojo.product.model.Spu;
import cn.tedu.mall.pojo.search.entity.SpuForElastic;
import cn.tedu.mall.product.service.front.IForFrontSpuService;
import cn.tedu.mall.search.repository.SpuForElasticRepository;
import cn.tedu.mall.search.service.ISearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class SearchServiceImpl implements ISearchService {
    @DubboReference
    private IForFrontSpuService dubboFrontSpuService;
    @Autowired
    private SpuForElasticRepository elasticRepository;

    //分页将数据加载到ES中
    @Override
    public void loadSpuByPage() {
        int i=1; //循环次数，也是页码
        int pages = 0; //总页数
        //至少要执行一次，do-while循环
        do{
            JsonPage<Spu> spus = dubboFrontSpuService.getSpuByPage(i, 2);
            //我们需要将Spu转换成SpuForElastic
            List<SpuForElastic> esSpus = new ArrayList<>();
            for (Spu spu : spus.getList()) {
                SpuForElastic spuForElastic = new SpuForElastic();
                BeanUtils.copyProperties(spu,spuForElastic);
                //放入esSpus集合中
                esSpus.add(spuForElastic);
            }
            //执行SpringDataES的批量新增方法
            elasticRepository.saveAll(esSpus);
            log.info("成功加载第{}页数据成功",i);
            //为下次循环做准备
            pages = spus.getTotalPage();
            i++;
        }while (i<=pages);
    }

    @Override
    public JsonPage<SpuForElastic> search(String keyword, Integer page, Integer pageSize) {
        //SpringData分页参数page如果是0才是第一页，PageHelper是1代表第一页
        Page<SpuForElastic> spus = elasticRepository.querySearch(keyword, PageRequest.of(page-1,pageSize));
        //将Page转成JsonPage
        JsonPage<SpuForElastic> jsonPage = new JsonPage<>();
        //当前页码
        jsonPage.setPage(page);
        //每页条数
        jsonPage.setPageSize(pageSize);
        //总页数
        jsonPage.setTotal(spus.getTotalElements());
        //总条数
        jsonPage.setTotalPage(spus.getTotalPages());
        //将查询的数据结果赋值给jsonPage
        jsonPage.setList(spus.getContent());
        //返回jsonPage
        return jsonPage;
    }
}
